package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.service.IStrategyCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;
    @Override
    public StrategyComment get(String id) {
        Optional<StrategyComment> optional = repository.findById(id);
        //如果数据库不是空的
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Autowired
    private MongoTemplate template;
    /**
     * 分页操作
     * @param qo 分页条件
     * @return
     */
    @Override
    public Page list(StrategyCommentQuery qo) {
        Query query = new Query();
        //在评论的分页操作中  只显示该攻略的评论  过滤一下
        if (StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }
        Page<StrategyComment> page = DBHelper.query(template, StrategyComment.class, query, qo.getPageable());
        return page;
    }

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setCreateTime(new Date());
        //判断点赞的list中有没有登陆者的id
        repository.save(strategyComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void commentThumb(String cid, UserInfo userInfo) {
        StrategyComment comment = this.get(cid);
        List<String> thumbuplist = comment.getThumbuplist();
        String id = userInfo.getId();
        //如果点赞的list有这个id
        //那么就删除
        if (thumbuplist.contains(id)){
            comment.setThumbupnum(comment.getThumbupnum()-1);
            thumbuplist.remove(id);
        }else {//没有的话就加上点赞数
            comment.setThumbupnum(comment.getThumbupnum()+1);
            thumbuplist.add(id);
        }
        repository.save(comment);
    }
}
